/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.alien.admin.modules.deploy.repository;

import com.alien.admin.modules.deploy.domain.DeployRec;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Map;

/**
* @website https://el-admin.vip
* @author zhouseyi
* @date 2021-09-22
**/
public interface DeployRecRepository extends JpaRepository<DeployRec, Long>, JpaSpecificationExecutor<DeployRec> {

    /**
     * @description: 查找最近一次编译记录
     * @author: zhouseyi
     * @date: 2021/9/23 16:31
     * @version: 1.0
     */
    DeployRec findFirstByProjectIdAndEnvOrderByIdDesc(Integer projectId, String env);

    /***
     * 查询部署状态，为了提高效率
     * @param id
     * @return
     */
    @Query(value = "select stage, deploy_status, project_id, project_name, operator_id from dp_deploy_rec where id = ?1", nativeQuery = true)
    Map<String, Object> findDeployStatus(Long id);

    /**
     * 删除某个环境下，时间点比deployTime早的记录。
     *
     * @param env
     * @param deployTime
     */
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    @Query(value = "delete from dp_deploy_rec where env=:env and deploy_time<=:deployTime", nativeQuery = true)
    void deleteByEnvAndDeployTime(@Param("env") String env, @Param("deployTime")Timestamp deployTime);
}
